filename = "../user_preferences"
telas = {["grupos"] = 0, ["matamata"] = 0}
tela = nil
t0 = 0
t1 = 0

function create_file()
	file, err = io.open(filename, "r")

	if (err ~= nil) then
		print('[t-cup]: Creating new user preferences file...')

		file = io.open(filename, "w")
		file:write("tela_preferida=grupos:0;matamata:0\n")
		file:write("gruposAB=0:0\n")
		file:write("gruposCD=0:0\n")
		file:write("gruposEF=0:0\n")
		file:write("gruposGH=0:0\n")
		file:write("sua_selecao=brazil\n")
	end
	
	file:close()

end

function loadscreen()
    create_file()
	for line in io.open(filename):lines() do
		telas["grupos"], telas["matamata"] = string.match(line, "^tela_preferida=grupos:([0-9]*);matamata:([0-9]*)$")

		if (telas["grupos"] ~= nil) then
			if (telas["grupos"] > telas["matamata"]) then
				tela = "grupos"
			else
				if (telas["grupos"] == telas["matamata"]) then
					tela = "principal"
				else
					tela = "matamata"
				end
			end
			break
		end
	end

	print('Tela preferida: ', tela)

	event.post('out', {class = 'ncl', type = 'presentation', action = 'start', label = tela})
	event.post('out', {class = 'ncl', type = 'presentation', action = 'stop', label = tela})
end

function save_access()
	local aa = ""
	local muda = 0

	file = io.open(filename, "r")
	for line in file:lines() do
		local linha = string.match(line, "^(tela_preferida)[a-zA-Z0-9:;=]*$")
		if (linha == 'tela_preferida') and (tela == 'grupos' or tela == 'matamata') then
			aa = aa .. 'tela_preferida=grupos:' .. (telas['grupos']) .. ';matamata:' .. (telas['matamata']) .. "\n"
			muda = 1
		else
			aa = aa .. line .. "\n"
		end
	end
	file:close()

	if (muda == 1) then
		file = io.open(filename, "w")
		file:write(aa)
		file:flush()
		file:close()
	end
end

function handler(evt)
	print('[tela]')
	print(evt.type, evt.name, evt.action, evt.value, evt.label)

	if (evt.class == 'ncl') and
	   (evt.type  == 'presentation') and
	   (evt.name == nil) and
	   (evt.action == 'start') then
		print('[t-cup]: Loading screen')
		loadscreen()
		t0 = os.time()
	elseif  (evt.type   == 'attribution') then
		if (evt.value == 'deixar') then
			t1 = os.time()

			if (os.difftime(t1, t0) > 10) then
				telas[tela] = telas[tela] + 1
				save_access()
			end
		end

		event.post('out', {class = evt.class, type = evt.type, name = evt.name, action = 'stop', value = evt.value})

		if (evt.value == 'deixar') then
			return
		elseif (evt.value == 'sair') then
			event.post('out', {class = 'ncl', type = 'presentation', name = nil, action = 'stop'})
			return
		else
			event.post('out', {class = 'ncl', type = 'presentation', action = 'start', label = evt.value})
			event.post('out', {class = 'ncl', type = 'presentation', action = 'stop', label = evt.value})
			tela = evt.value

			t0 = os.time()
		end

		print('[t-cup]: Iniciando tela: '..tela)
	end
end

event.register(handler)
